#pragma once

#include <functional>
#include <strings.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include "InetAddr.hpp" 

using func_t = std::function<void(int sockfd, std::string message, InetAddr cliAddr)>;

enum
{
    SOCKET_ERROR = 1, // 套接字错误
    BIND_ERROR,       // 绑定错误
};

class UdpServer
{
public:
    UdpServer(uint16_t port, func_t callback)
        : _port(port)
        , _callback(callback)
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
            exit(SOCKET_ERROR);

        struct sockaddr_in addr;
        bzero(&addr, sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_port = htons(_port);
        addr.sin_addr.s_addr = INADDR_ANY;

        // 绑定
        int n = bind(_sockfd, (struct sockaddr*)&addr, sizeof(addr));
        if (n < 0)
            exit(BIND_ERROR);
    }

    void start()
    {
        while (true)
        {
            char buffer[1024];
            struct sockaddr_in cliAddr;
            bzero(&cliAddr, sizeof(cliAddr));
            socklen_t len = sizeof(cliAddr);

            int n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (sockaddr*)&cliAddr, &len);
            if (n > 0)
            {
                buffer[n] = '\0';
                _callback(_sockfd, buffer, cliAddr);
            }
        }
    }

private:
    int _sockfd;
    uint16_t _port;
    func_t _callback;
};
